package com.example.mutildatasource.service.impl;

import com.example.mutildatasource.entity.User;
import com.example.mutildatasource.mapper.secondary.UserMapper;
import com.example.mutildatasource.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * Spring默认的只会对运行时的异常进行事务回滚，使用try catch必须抛出RuntimeException
     * 否则try catch普通的异常，不会回滚，出现脏数据。
     */
    @Override
    @PostConstruct
    @Transactional(value = "secondaryTransactionManager",rollbackFor={Exception.class})
    public void insertUser() {
        try {
            this.initExecMethod();
//            测试事务，user表用户名不能为空
            User user2 = new User();
//            user2.setUserName("Lucy");
            user2.setPassword("root");
            user2.setSex("女");
            this.userMapper.insertUser(user2);

            User user3 = new User("lisi","root","男");
            this.userMapper.insertUser(user3);

        }catch (Exception e){
            throw new RuntimeException(e.toString());
        }
    }

    public void initExecMethod(){
        User user1 = new User("zhangsan","root","男");
        this.userMapper.insertUser(user1);
    }

}
